package me.mysearch;

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 5, 6, 7, 8, 9};
        int result = binarySearchBasic(arr, 7);
        System.out.println(result);
    }

    public static int binarySearchBasic(int[] a, int target) {
        //设置指针和初值
        /*int i = 0, j = a.length - 1;
        while (i <= j) {
            int m = (i + j) / 2;
            if (a[m] > target) {
                j = m - 1;
            } else if (a[m] < target) {
                i = m + 1;
            } else {
                return m;
            }
        }
        return -1;*/

        //防止索引变成负数
        //这里采用右移一位
        int i = 0, j = a.length - 1;
        while (i <= j) {
            int m = (i + j) >>> 1;
            if (target < a[m]) {
                j = m - 1;
            } else if (a[m] < target) {
                i = m + 1;
            } else {
                return m;
            }
        }
        return -1;

    }
}
